<template>
    <!-- 判断渲染上传图片 -->
    <div v-if="modelValue">
        <el-image :src="modelValue" fit="cover" class="w-[100px] h-[100px] rounded border mr-2"></el-image>
    </div>
    <div class="choose-image-btn" @click="open">
        <el-icon :size="25" class="text-gray-500"><Plus /></el-icon>
    </div>
    <el-dialog
        title="选中图片"
        v-model="dialogVisible"
        width="80%"
        top="5vh"
    >
        <el-container class="bg-white rounded" style="height: 70vh;">
            <el-header class="image-header">
                <el-button type="primary" size="small" @click="handleOpenCreate">
                    新增图片分类
                </el-button>
                <el-button type="warning" size="small" @click="handleUpload">
                    上传图片
                </el-button>
            </el-header>
            <el-container>
                <ImageAside ref="ImageAsideRef" @change="handleAsideChange"/>
                <ImageMain :choose="true" ref="ImageMainRef" @choose="handleChoose"/>
            </el-container>
        </el-container>
        <span></span>
        <template #footer>
            <span>
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="submit">确定</el-button>
            </span>
        </template>
    </el-dialog>
    
</template>

<script setup>
import { ref } from 'vue'
// 引入分离后的组件
import ImageAside from '~/components/ImageAside.vue'
import ImageMain from '~/components/ImageMain.vue'

// 对话框显隐
const dialogVisible = ref(false)

// 接收子组件过来的参数
const ImageAsideRef = ref(null)

// 调用新增或修改图片打开抽屉方法
const handleOpenCreate = () => ImageAsideRef.value.handleCreate()

// 调用打开上传图片抽屉方法
const handleUpload = () => ImageMainRef.value.upLoadFileOpen()

// 接收子组件传过来的参数
const ImageMainRef = ref(null)

// 用子组件方法渲染右侧图片列表
const handleAsideChange = (image_class_id) => ImageMainRef.value.loadImageData(image_class_id)

// 打开对话框方法
const open = () => {
    dialogVisible.value = true
}

// 关闭对话框方法
const close = () => {
    dialogVisible.value = false
}

// 接收父组件表单传过来的绑定值
const props = defineProps({
    modelValue: [String,Array]
})

// 子组件改变父组件表单的值
const emit = defineEmits(['update:modelValue'])

// 设计空数组接收传过来的图片地址
let urls = []

// 从子组件获得的选中图片
const handleChoose = (choose) =>{
    urls = choose.map(item => item.url)
}

const submit = () => {
    if(urls.length){
        // 父组件将图片地址传递给子组件
        emit('update:modelValue',urls[0])
        // 关闭对话框
        close()
    }
}


</script>


<style scoped>
.choose-image-btn{
    @apply w-[100px] h-[100px] flex items-center justify-center curisor-pointer rounded border 
    hover:(bg-gray-100);
}
/* 配合position属性和overflow属性，实现滚动条 */
.image-header{
    border-bottom: 1px solid #eeeeee;
    @apply flex items-center;
}
</style>

